package com.orhon.smartcampus.modules.notice.dao;

import com.orhon.smartcampus.basicComponents.baseDao.BaseDaoImpl;
import com.orhon.smartcampus.modules.notice.entity.NoticeAndSchool;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.util.List;

@Component
public class NoticeAndUserDao extends BaseDaoImpl<NoticeAndSchool> {

    @Transactional
    public void insert(NoticeAndSchool entity) {
        Session session = this.getSession();
        session.save(entity);
    }

    @Transactional
    public void update(NoticeAndSchool entity){
        Long notice_id=entity.getNotice_id();
        Session session =null;
        try {
            session=this.getSession();
            StringBuffer sb = new StringBuffer("delete base_notice_user_relation where notice_id = :notice_id");
            Query query = session.createSQLQuery(sb.toString()).setParameter("notice_id",notice_id);
            //session.update(entity);
            query.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Transactional
    public List usersList(Long notice_id){
        Session session = this.getSession();
        StringBuffer sb = new StringBuffer("select id,notice_id,user_id from base_notice_user_relation where notice_id = :notice_id");
        Query query = session.createSQLQuery(sb.toString()).setParameter("notice_id",notice_id);
        List<NoticeAndSchool> noticeAndUsers = this.find("from NoticeAndSchool where notice_id = " + notice_id);
        return  noticeAndUsers;
    }
    @Transactional
    public Integer count(Long notice_id){
        Session session = this.getSession();
        StringBuffer sb = new StringBuffer("select count(*) from base_notice_user_relation where notice_id= :notice_id");
        Query query = session.createSQLQuery(sb.toString()).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).setParameter("notice_id",notice_id);
        return  query.list().size();
    }
}
